package com.leyou.item.controller;

import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * http://api.leyou.com/api/item/spec/groups/3
 * http://api.leyou.com/api/item/spec/params?cid=77
 *
 * @author linzx
 * @date 2020/3/25
 */
@RestController
@RequestMapping("spec")
public class SpecController {
    @Autowired
    private SpecGroupService specGroupService;
    @Autowired
    private SpecParamService specParamService;

    /**
     * 根据cid查找SpecGroup
     * @param cid
     * @return
     */
    @GetMapping("groups/{cid}")
    public ResponseEntity<List<SpecGroup>> findSpecGroupByCid(@PathVariable("cid") Long cid) {

        return ResponseEntity.ok(specGroupService.findSpecGroupWithSpecParamsByCid(cid));
    }

    @PutMapping("group")
    public ResponseEntity<Void> updateSpecGroup(@RequestBody SpecGroup specGroup) {
        int i = specGroupService.updateByPrimaryKeySelective(specGroup);
        return i == 1 ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }

    @PostMapping("group")
    public ResponseEntity<Void> addSpecGroup(@RequestBody SpecGroup specGroup) {
        int i = specGroupService.insertSelective(specGroup);

        return i == 1 ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }

    @DeleteMapping("group/{id}")
    public ResponseEntity<Void> deleteSpecGroupById(@PathVariable("id") Long id) {
        int i = specGroupService.deleteByPrimaryKey(id);
        return i == 1 ? ResponseEntity.ok().build() : ResponseEntity.badRequest().build();
    }


    /**
     * 根据参数查找SpecParam
     * @param cid
     * @param gid
     * @param searching
     * @return
     */
    @GetMapping("params")
    public ResponseEntity<List<SpecParam>> findSpecByParams(
            @RequestParam(value = "cid", required = false) Long cid,
            @RequestParam(value = "gid", required = false) Long gid,
            @RequestParam(value = "searching", required = false) Boolean searching
    ) {
        SpecParam specParam = new SpecParam();
        specParam.set(cid, gid, searching);
        List<SpecParam> specParamList = specParamService.select(specParam);
        return ResponseEntity.ok(specParamList);
    }

}
